<script setup>
import { ref, reactive, onMounted, defineProps } from 'vue';
import { getImageUrl } from '@/utils/request.js';
import { useRoute, useRouter } from 'vue-router'; //路由器
import { showToast } from 'vant';//轻提示
import { showNotify } from 'vant';
import { HorizontalN, RectLeft } from '@nutui/icons-vue';
import CommentList from './CommentListView.vue';
import GoodsDetailView from './GoodsDetailView.vue'
import http from '@/utils/request.js';
const props = defineProps(['goodsId']);
const goodsId = props.goodsId;
console.log('goodsId = ', goodsId);

const tab2value = ref(0);
//显示更多
const right = () => {
    console.log('更多');
}
const changeTabList = (tab) => {
    tab2value.value = tab.paneKey;
    console.log('当前被点击：', tab, tab2value.value)
};
//显示弹出层
const showTop = ref(false);

//获取路由对象
const route = useRoute();
//获取到 router 对象，用于编程式跳转导航
const router = useRouter();
console.log('router 路由器 = ', router);
console.log('route 路由 = ', route);
//route.params.xxx 获取路径参数
console.log('goodslist.goodsId = ', route.params.goodsId);
//居中对齐
const align = ref('center');
//购买商品数量
const value = ref(1);
//用户留言
const message = ref('');
//商品图片
const goodsUrl = ref("");
//收藏图标及提示
let val = 0;
const color = ref("black");
const collect = () => {
    val++;
    if (val == 1) {
        color.value = "red";
        showToast({
            message: '收藏成功！',
            icon: 'like-o',
        });
        saveCollect();
    } else if (val == 2) {
        color.value = "black";
        showToast({
            message: '取消收藏！',
            icon: 'like-o',
        });
        delCollect();
        val = 0
    }
}
//弹出层
const show = ref(false);
//展示弹出层
const showPopup = () => {
    show.value = true;
};
//关闭弹出层
const closePopup = () => {
    show.value = false;
};
const showVal = ref(false);
const showOrder = () => {
    showVal.value = true;
}
const onSubmit = () => {
    console.log('提交订单');
}
const banners = ref([]);
const getBannerList = function () {
    http.get('/goods/banner/1').then(res => {
        console.log('获取轮播图列表：', res.data.data);
        banners.value = res.data.data;
        console.log('banners：', banners);
    }).catch(err => {
        console.log(err);
    });
}

//跳转到首页
function toFirstPageView() {
    router.push("/");
}
//跳转到商品分类页面
function toGoodsType() {
    router.push("/goodstype");
}
//跳转到发布闲置页面
function toPublishView() {
    router.push("/fabuxianzhi");
}
//跳转到消息页面
function toMessageView() {
    router.push("/messagelist");
}
//跳转到个人页面
function toPersonalView() {
    router.push("/personal");
}
//跳转到首页
function toPreviousPageView() {
    router.push("/shouye");
}
//商品信息
let goodsInfo = reactive({
    id: '',
    name: '',
    brand: '',
    type: '',
    money: '',
    extent: '',
    production: '',
    sellerName: '',
    image: ''
})
//用户信息
let userInfo = reactive({
    userName: '',
    phone: '',
    address: '',
})
//收藏商品
let goodsCollect = reactive({
    sellerId: '0',
    goodsId: '',
    goodsType: '',
    goodsName: '',
    userId: '',
})
// 获取个人信息  
const getUserInfo = function () {
    http.get("/user/info").then((response) => {
        console.log("获取个人信息= ", response.data);
        userInfo.address = response.data.data.address;
        userInfo.userName = response.data.data.userName;
        userInfo.phone = response.data.data.phoneNum;
        goodsCollect.userId = response.data.data.id;
    }).catch(() => {
    });
}
//获取商品信息
const getGoodsInfo = function () {
    http.get('/user/goods/' + route.params.goodsId).then((res) => {
        console.log('查询到的商品信息：', res.data);
        goodsInfo.id = res.data.data.goodsId;
        goodsInfo.name = res.data.data.goodsName;
        goodsInfo.brand = res.data.data.brand;
        goodsInfo.type = res.data.data.goodsType;
        goodsInfo.money = res.data.data.price;
        goodsInfo.extent = res.data.data.quality;
        goodsInfo.production = res.data.data.details;
        goodsInfo.sellerName = res.data.data.sellerName;
        goodsInfo.image = res.data.data.picture;
        goodsCollect.goodsId = res.data.data.goodsId;
        goodsCollect.goodsType = res.data.data.goodsType;
        goodsCollect.goodsName = res.data.data.goodsName;;
    });
}
//添加收藏
const saveCollect = function () {
    console.log('收藏信息sellerId：', goodsCollect.sellerId);
    console.log('收藏信息goodsId：', goodsCollect.goodsId);
    console.log('收藏信息goodsType：', goodsCollect.goodsType);
    console.log('收藏信息goodsName：', goodsCollect.goodsName);
    console.log('收藏信息userId：', goodsCollect.userId);
    http.post('/collect/add', goodsCollect).then((res) => {
        console.log('收藏成功！', res);
    }).catch(function (error) {
        // 处理错误情况
        console.log('收藏失败！', error);
    });
}

const addressLists = reactive({
phoneNum: '',
    name: '',
    address: '',
})
// 获取地址列表  
const getAddressList = () => {
    // console.log("------------" + user.value);
    http.get("/user/info").then((response) => {
        console.log("获取个人信息= ", response);
        console.log("id:", response.data.data.id);
        http.get("/address/list/" + response.data.data.id).then((res) => {
            console.log('获取地址列表: ', res.data.data.list);
                addressLists.address = res.data.data.list[0].address;
                addressLists.phoneNum = res.data.data.list[0].phoneNum;
                addressLists.name = res.data.data.list[0].userName;
            console.log('addressLists:', addressLists.name);
            // resolve(); // 当获取待收货列表成功后，返回一个解析成功的Promise  
        }).catch(err => {
            console.log(err);//reject(err); // 当请求失败时，返回一个请求失败的Promise  
        });

    }).catch(() => {
    });
};

// 地址 TODO需换成个人地址列表和新增方法
// 地址列表
const showPopupExist = ref(false);
const showEditDialog = ref(false);
let addId = ref('')
const handleEdit = () => {
    showEditDialog.value = true;
   

};
//编辑地址
const address = reactive({
    addId: '',
    phoneNum: '',
    name: '',
    address: '',
    userId: ''
})

const text = ref('选择地址');

const showAddressExist = () => {
    showPopupExist.value = true;
};

const close = (val) => {
    if (val.type == 'exist') {
        const { provinceName, cityName, countyName, townName, addressDetail } = val.data;
        text.value = provinceName + cityName + countyName + townName + addressDetail;
    } else {
        text.value = val.data.addressStr;
    }
};

const selected = (prevExistAdd, nowExistAdd, arr) => {
    console.log(prevExistAdd);
    console.log(nowExistAdd);
};



// 新增订单
const order = reactive({
    address: '',
    sellerName: '',
    amount: '',
    orderNumber: '',
    orderTime: '',
    details: '',
    goodsName: '',
    orderPrice: '',
    payTime: '',
    orderState: '',
    phoneNum:'',
    price: '',
    userName: ''
})

const onFailed = () => {
    showNotify({ type: 'success', message: '通知内容' });
}
const addOrder = () => {
    order.goodsId = route.params.goodsId;
    order.address = addressLists.address;
    order.phoneNum= addressLists.phoneNum;
    order.userName = userInfo.userName;
    // 二次确认
    http.post("/user/order", order)
        .then((res) => {
            console.log('!!!!!!!!!!!!!!!!!返回值：', res.data);
            const { code, message } = res.data;
            console.log("=========code", code);
            if (200 === code) {
                showNotify({ type: 'success', message: '下单成功,请尽快支付' });
                setTimeout(() => {
                    router.push("/beforepay");
                }, 1000);
            } else {
                showNotify({ type: 'danger', message });
            }
        }).catch((err) => {
            // console.log('下单失败：', err);
            // ElMessage.error(`失败`);

        });
}



//取消收藏
const delCollect = function () {
    http.delete('/collect/' + route.params.goodsId).then((res) => {
        console.log('要删除的收藏信息', res.data);
    })
}
onMounted(() => {
    getUserInfo();
    getGoodsInfo();
    getBannerList();
    getAddressList();
    console.log("地址：",addressLists)
})
//跳转到选择地址
function toAddressView() {
    router.push("/setting");
    console.log('选择地址。');




}
const onClickRight = () => history.back();
</script>
<template>
    <van-col class="img">
        <van-swipe :autoplay="5000">
            <van-swipe-item >
                <img :src="getImageUrl(goodsInfo.image)" :width="400" :height="400" />
            </van-swipe-item>
        </van-swipe>
    </van-col>

    <nut-navbar @click-right="onClickRight" :fixed="true">
        <template #content>
            <nut-tabs v-model="tab2value" @click="changeTabList">
                <nut-tab-pane title="商品"> </nut-tab-pane>
                <nut-tab-pane title="评价"> </nut-tab-pane>
                <nut-tab-pane title="详情"> </nut-tab-pane>
            </nut-tabs>
        </template>
        <template #right>
            <HorizontalN class="right" width="16px" @click="showTop = true"></HorizontalN>
        </template>
        <template #left>
            <RectLeft class="left" width="16px" @click="toPreviousPageView"></RectLeft>
        </template>
    </nut-navbar>
    
    <div v-if="tab2value == 1">
        <CommentList />
    </div>
    <div v-else-if="tab2value == 2">
        <GoodsDetailView />
    </div>
    <nut-popup position="top" closeable :style="{ height: '20%' }" teleport-disable v-model:visible="showTop">
        <van-col offset="2">
            <div class="font">快捷入口</div>
        </van-col>
        <nut-row type="flex" justify="space-evenly" class="popup">
            <nut-col :span="4" align="center" @click="toFirstPageView">
                <IconFont name="home" size="30"></IconFont>
                <div>首页</div>
            </nut-col>
            <nut-col :span="4" align="center" @click="toGoodsType">
                <IconFont name="category" size="30"></IconFont>
                <div>分类</div>
            </nut-col>
            <nut-col :span="4" align="center" @click="toPublishView">
                <IconFont name="share-n" size="30"></IconFont>
                <div>发布闲置</div>
            </nut-col>
            <nut-col :span="4" align="center" @click="toMessageView">
                <IconFont name="message" size="30"></IconFont>
                <div>消息</div>
            </nut-col>
            <nut-col :span="4" align="center" @click="toPersonalView">
                <IconFont name="people" size="30"></IconFont>
                <div>个人主页</div>
            </nut-col>
        </nut-row>
    </nut-popup>
    <van-col class="img">
        <van-swipe :autoplay="5000">
            <van-swipe-item v-for="img in imgs">
                <img :src="img" :width="400" :height="400" />
            </van-swipe-item>
        </van-swipe>
    </van-col>
    <van-col class="form">
        <van-col offset="1">
            <van-row>
                <p style="font-size: 25px;">￥{{ goodsInfo.money }}</p>
            </van-row>
        </van-col>
        <van-row gutter="10">
            <van-col offset="1">
                <van-tag plain type="danger" size="large">7天包换</van-tag>
            </van-col>
            <van-col>
                <van-tag plain type="danger" size="large">180天保修</van-tag>
            </van-col>
            <van-col>
                <van-tag plain type="danger" size="large">限购</van-tag>
            </van-col>
            <van-col>
                <van-tag plain type="danger" size="large">最高减1000元</van-tag>
            </van-col>
        </van-row>
        <van-col offset="1">
            <van-tag color="#ffe1e1" text-color="#ad0000" size="large" style="font-size: 10px;" class="tag">{{
                goodsInfo.extent }}</van-tag>
            <p style="font-size: 20px;">{{ goodsInfo.name }}</p>
            <van-text-ellipsis rows="1" :content="goodsInfo.production" expand-text="展开" collapse-text="收起"
                style="font-size: 18px;" />
        </van-col>
    </van-col>
    <van-col class="form">
        <van-cell title="已选" :border="false">
            <!-- 使用 title 插槽来自定义标题 -->
            <template #value>
                <span class="custom-title">{{ goodsInfo.name }}X{{ order.amount }}</span>
            </template>
        </van-cell>

        <!-- <van-row justify="end" style="font-size: 10px;color: red;" @click="toAddressView">地址不对？选择你的地址...</van-row> -->
        <van-row gutter="20">
            <van-col offset="1"><van-tag plain type="primary">✅100元以上免邮费</van-tag></van-col>
            <van-col><van-tag plain type="primary">✅7天无理由退货</van-tag></van-col>
        </van-row>
        <van-row gutter="20">
            <van-col offset="1"><van-tag plain type="primary">✅顺丰发货&快速到家</van-tag></van-col>
            <van-col><van-tag plain type="primary">✅上午下单，下午发货</van-tag></van-col>
            <van-col><van-tag plain type="primary">✅晚发赔</van-tag></van-col>
        </van-row>
    </van-col>
    <van-action-bar>
        <van-col @click="collect"><van-row justify="center"><van-icon name="star-o"
                    :color="color" /></van-row><span>收藏</span></van-col>
        <van-action-bar-button type="danger" text="选规格" @click="showPopup" />
        <van-action-bar-button type="danger" text="立即购买" @click="showOrder" />
    </van-action-bar>
    <van-popup v-model:show="show" closeable position="bottom" :style="{ height: '70%' }">
        <van-space :align="align" size="2rem">
            <van-col>
                <van-image width="150" height="150" :src="goodsUrl" class="goods_img" />
            </van-col>
            <van-col>
                <van-col style="color: red;font-size: 40px;font-family:Arial, Helvetica, sans-serif;">￥{{
                    goodsInfo.money }}</van-col>
                <van-col style="font-family: 'Times New Roman', Times, serif;">商品名称:{{
                    goodsInfo.name }}</van-col>
            </van-col>
        </van-space>
        <van-col offset="1" style="position: relative;top: 20px;font-size: 20px;">
            <van-row style="font-family: 'Times New Roman', Times, serif;">商品编号:{{
                goodsInfo.id }}</van-row>
            <van-row style="font-family: 'Times New Roman', Times, serif;position: relative;top: 2px;">商品类型:{{
                goodsInfo.type }}</van-row>
            <van-col style="font-family: 'Times New Roman', Times, serif;">商品描述:{{
                goodsInfo.production
            }}</van-col>
            <van-row justify="space-between">
                <van-col style="font-family: 'Times New Roman', Times, serif;">数量</van-col>
                <van-stepper v-model="order.amount" @overlimit="showToast('最少购买1件哦！');" />

            </van-row>
        </van-col>
        <van-action-bar>
            <van-action-bar-button type="danger" text="确定" round="true" size="large" @click="closePopup" />
        </van-action-bar>
    </van-popup>
    <van-popup v-model:show="showVal" closeable close-icon="arrow-left" close-icon-position="top-left" position="bottom"
        :style="{ height: '100%' }">
        <van-row justify="center">
            <van-col style="font-size: 20px;position: relative;top: 13px;">确认订单</van-col>
        </van-row>
        <van-cell-group inset style="margin-top: 10px;">
            <nut-cell title="地址" :desc="text" is-link > {{ addressLists.address }}</nut-cell>
            <nut-cell title="手机号" :desc="text" is-link > {{ addressLists.phoneNum}}</nut-cell>


        </van-cell-group>

        <!-- 可以使用 CellGroup 作为容器 -->
        <van-cell-group style="position: relative;top: 0px; background-color: #FFF5EE;" inset="true">
            <van-card :num="order.amount" :price="goodsInfo.money" :desc="goodsInfo.production" :title="goodsInfo.name"
                :thumb="goodsUrl" style="position: relative;top: 10px; background-color: #FFF5EE;" /><br>
        </van-cell-group>
        <van-divider :style="{ color: '#E0FFFF', borderColor: '#E0FFFF' }" style="position: relative;top: -10px; " />
        <van-cell-group style="position: relative;top: -22px; ">
            <van-cell title="商品金额">
                <template #value>
                    <span class="custom-title">￥{{ goodsInfo.money }}</span>
                </template>
            </van-cell>
            <van-cell title="商品数量">
                <template #value>
                    <span class="custom-title">x{{ order.amount }}</span>
                </template>
            </van-cell>
            <van-cell title="合计">
                <template #value>
                    <span class="custom-title">￥{{ goodsInfo.money * order.amount }}</span>
                </template>
            </van-cell>
            <van-field v-model="message" rows="2" autosize label="" type="textarea" maxlength="50" placeholder="请输入备注信息"
                show-word-limit />
        </van-cell-group>
        <van-submit-bar :decimal-length="2" :price="goodsInfo.money * 100 * order.amount" button-text="提交订单"
            @submit="addOrder" @failed="onFailed" />
    </van-popup>
</template>
<style>
.img {
    margin: -15px -16px;
}

.form {
    background-color: ghostwhite;
    margin: 10px -10px;
    border-radius: 10px;
    padding-top: 5px;
    padding-bottom: 5px;
}

.tag {
    position: relative;
    top: 5px;
}

.goods_img {
    position: relative;
    top: 20px;
    left: 20px;
}

:root:root {
    --van-cell-background: ghostwhite;
    --van-card-price-color: red;
    --van-card-thumb-size: 130px;
    --van-card-font-size: 18px;
}

.font {
    position: relative;
    top: 20px;
}

.popup {
    position: relative;
    top: 50px;
}

:root {
    --nut-navbar-padding: 0 -20px;
}

header {
    position: fixed;
    top: 0;
    width: 100%;
    z-index: 9999;
    line-height: 1.5;
    max-height: 100vh;
}


header {
    line-height: 1.5;
    max-height: 100vh;
}


nav {
    width: 100%;
    font-size: 12px;
    text-align: center;
    margin-top: 2rem;
}

nav a.router-link-exact-active {
    color: var(--color-text);
}

nav a.router-link-exact-active:hover {
    background-color: transparent;
}

nav a {
    display: inline-block;
    padding: 0 1rem;
    border-left: 1px solid var(--color-border);
}

nav a:first-of-type {
    border: 0;
}

@media (min-width: 1024px) {
    header {
        display: flex;
        place-items: center;
        padding-right: calc(var(--section-gap) / 2);
    }


    header .wrapper {
        display: flex;
        place-items: flex-start;
        flex-wrap: wrap;
    }

    nav {
        text-align: left;
        margin-left: -1rem;
        font-size: 1rem;
        padding: 1rem 0;
        margin-top: 1rem;
    }
}

.van-field {
    /* 调整每一行边距 */
    padding: 16px 15px;
}

.van-nav-bar {
    color: #d4e09f;
    width: 100%;
}

.full-width-card {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    padding: 10px;
    /* 根据需要调整 */
}

.nav_bar {
    position: relative;
    top: -32px;
    /* left:-32px;
    right: -32px; */
    margin: 2px -32px
}
</style>